/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2015年4月11日 下午8:38:36
 * @Description: 本内容未经本人允许禁止使用、转发.
 */

package com.ls.fw.web.demo.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ls.fw.web.activiti.base.BaseActivitiController;
import com.ls.fw.web.demo.util.UserUtil;

/**
 * 
 * @author lisheng
 * @date 2015年4月11日 下午8:38:36
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/auth")
public class AuthController extends BaseActivitiController {

	@RequestMapping(value = "/login")
	public String logon(@RequestParam("username") String userName,
			@RequestParam("password") String password, HttpSession session) {
		logger.debug("logon request: {username={}, password={}}", userName,
				password);
		boolean checkPassword = identityService.checkPassword(userName,
				password);
		if (checkPassword) {

			// 查看用户是否存在
			User user = identityService.createUserQuery().userId(userName)
					.singleResult();
			UserUtil.saveUserToSession(session, user);

			/*
			 * 读取角色
			 */
			List<Group> groupList = identityService.createGroupQuery()
					.groupMember(user.getId()).list();
			session.setAttribute("groups", groupList);

			String[] groupNames = new String[groupList.size()];
			for (int i = 0; i < groupNames.length; i++) {
				groupNames[i] = groupList.get(i).getName();
			}
			session.setAttribute("groupNames", ArrayUtils.toString(groupNames));

			return "redirect:/main/index";
		} else {
			return "redirect:/login.jsp?error=true";
		}
	}

	/**
	 * 退出登录
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpSession session) {
		session.removeAttribute(UserUtil.USER);
		return "/login";
	}
}
